package znet

import (
	"bytes"
	"encoding/binary"
	"zinx/ziface"
)

type DataPack struct {}

func NewDataPack() *DataPack {
	return &DataPack{}
}

func (db *DataPack) GetHeadLen() uint32 {
	return 8
}

func (db *DataPack) Pack(msg ziface.IMessage)([]byte,error) {
	dataBuff := bytes.NewBuffer([]byte{})

	if err := binary.Write(dataBuff,binary.LittleEndian,msg.GetDataLen()); err != nil {
		return nil,err
	}

	if err := binary.Write(dataBuff,binary.LittleEndian,msg.GetMsgId()); err != nil {
		return nil,err
	}
	if err := binary.Write(dataBuff,binary.LittleEndian,msg.GetData()); err != nil {
		return nil,err
	}
	
	return dataBuff.Bytes(),nil
}

func (db *DataPack) Unpack(binaryData []byte)(ziface.IMessage,error) {
	dataBuff := bytes.NewBuffer(binaryData)

	msg := &Message{}

	if err := binary.Read(dataBuff,binary.LittleEndian,&msg.DataLen); err != nil {
		return nil,err
	}
	if err := binary.Read(dataBuff,binary.LittleEndian,&msg.Id); err != nil {
		return nil,err
	}
	
	return msg,nil
}


